<template>
  <div>
    <div>
      <el-card class="box-card">
        <div slot="header" class="clearfix">
          <span>sql正则替换</span>
          <div style="float: right">
            <el-button size="small">
              <el-upload ref="upload" :on-change="handleUpFile" :auto-upload="false" action="#" :show-file-list="false"
                :limit="1">
                点击上传
              </el-upload>
            </el-button>
            <el-button type="primary" size="small" @click="handleReplace" :disabled="!sqlContent">确认转换</el-button>
            <el-button type="success" size="small" @click="handleDown" :disabled="!sqlContented">下载</el-button>
          </div>
        </div>
        <div>
          <el-row>
            <el-col :span="11">
              <div class="grid-content bg-purple">
                <span>需要转换：</span>
                <el-radio-group v-model="sqlSelectVal" @change="handleClean('sqlContented')">
                  <el-radio :label="item.value" v-for="(item, index) in sqlSelectValData" :key="index">{{ item.label
                    }}</el-radio>
                </el-radio-group>
                <div style="height: 10px"></div>
                <el-input type="textarea" placeholder="请输入sql语句" resize="none" v-model="sqlContent">
                </el-input>
              </div>
            </el-col>
            <el-col :span="2">
              <div class="grid-content bg-purple center">
                <i class="el-icon-right"></i>
              </div>
            </el-col>
            <el-col :span="11">
              <div class="grid-content bg-purple">
                <span>转换后：</span>
                <el-radio-group v-model="sqlSelectedVal">
                  <el-radio :label="item.value" v-for="(item, index) in sqlSelectedValData" :key="index">{{ item.label
                    }}</el-radio>
                  <div style="display: inline-block; width: 200px">
                    <el-input v-model="modVal" size="mini" placeholder="请输入Kingbase模型"></el-input>
                  </div>
                </el-radio-group>
                <div style="height: 10px"></div>
                <el-input type="textarea" placeholder="转换后的sql" resize="none" v-model="sqlContented">
                </el-input>
              </div>
            </el-col>
          </el-row>
        </div>
      </el-card>
    </div>

    <div style="margin: 10px 0"></div>
    
    <div>
      <el-card class="box-card">
        <div slot="header" class="clearfix">
          <span>正则列表</span>
        </div>
        <div>
          <el-table :data="regData" style="width: 100%">
            <el-table-column label="序列" type="index" width="60" align="center">
            </el-table-column>
            <el-table-column label="提示" prop="tips" width="180">
            </el-table-column>
            <el-table-column label="正则" prop="reg">
              <template slot-scope="scope">
                <pre>{{ scope.row.reg }}</pre>
              </template>
            </el-table-column>
            <el-table-column label="用例" prop="data"></el-table-column>
          </el-table>
        </div>
      </el-card>
    </div>
  </div>
</template>
<script>
import axios from "axios";
export default {
  data() {
    return {
      sqlContent: "", //sql语句内容
      sqlContented: "", //sql转换后语句内容
      sqlSelectVal: "Oracle", //需要转换的sql名字
      sqlSelectedVal: "Kingbase",
      modVal: "", //模型
      sqlSelectValData: [
        {
          value: "Oracle",
          label: "Oracle",
        },
      ],
      sqlSelectedValData: [
        {
          value: "Kingbase",
          label: "Kingbase（金仓）",
        },
      ],
      upFilesName: "",
      regData: [
        {
          reg: `/NOT DEFERRABLE INITIALLY IMMEDIATE NORELY VALIDATE|"WEBSITE"./g,''`,
          tips: "去掉错误语法",
          fg: (str) => {
            return str.replace(
              /NOT DEFERRABLE INITIALLY IMMEDIATE NORELY VALIDATE|"WEBSITE"./g,
              ""
            );
          },
        },
        {
          reg: `/INSERT\s+INTO\s+(\w+)\s*\(.*?\)\s*VALUES\s*\(.*?\)/g`,
          data: `INSERT INTO myep(id,name) VALUES(2,'张4');`,
          tips: "新增数据",
          fg: (str) => {
            let regex = /INSERT\s+INTO\s+(\w+)\s*\(.*?\)\s*VALUES\s*\(.*?\)/g;
            return str.replace(regex, (match, tableName) => {
              return `INSERT INTO "${tableName}"${match.slice(
                match.indexOf("(")
              )}`;
            });
          },
        },
        {
          reg: `/UPDATE\s+(\w+)\s+SET/g`,
          data: `UPDATE myep SET name = 'sen224',job = 'joke', job22 = 'joke' WHERE id = 2;`,
          tips: "修改数据",
          fg: (str) => {
            let regex = /UPDATE\s+(\w+)\s+SET/g;
            return str.replace(regex, (match, tableName) => {
              return `UPDATE "${tableName}" SET`;
            });
          },
        },
        {
          reg: `/DELETE\s+FROM\s+(\w+)\s+WHERE/g`,
          data: `DELETE FROM myep WHERE id = 1;`,
          tips: "删除数据",
          fg: (str) => {
            let regex = /DELETE\s+FROM\s+(\w+)\s+WHERE/g;
            return str.replace(regex, (match, tableName) => {
              return `DELETE FROM "${tableName}" WHERE`;
            });
          },
        },
        // 					{
        // 						reg: `/DELETE FROM (\w+) WHERE (.*)/g,"DELETE FROM $1 USING $1 WHERE $2"
        // /INSERT INTO (\w+)\s*\(.*\)\s*VALUES \((.*)\)/g,"INSERT INTO $1 ($2) VALUES ($3)"
        // /UPDATE (\w+) SET (.*) WHERE (.*)/g,"UPDATE $1 SET $2 WHERE $3"`,
        // 						tips: "增删改",
        // 						fg: str => {
        // 							let kingbaseDDL = str.replace(/DELETE FROM (\w+) WHERE (.*)/g,"DELETE FROM $1 USING $1 WHERE $2");
        // 							kingbaseDDL = kingbaseDDL.replace(/INSERT INTO (\w+)\s*\(.*\)\s*VALUES \((.*)\)/g,"INSERT INTO $1 ($2) VALUES ($3)");
        // 							kingbaseDDL = kingbaseDDL.replace(/UPDATE (\w+) SET (.*) WHERE (.*)/g,"UPDATE $1 SET $2 WHERE $3");
        // 							kingbaseDDL = kingbaseDDL.replaceAll(`"WEBSITE".`,'');
        // 							return kingbaseDDL;
        // 						}
        // 					},
      ],
    };
  },
  methods: {
    async handleUpFile(options) {
      this.upFilesName = options.name;
      let url = window.URL.createObjectURL(options.raw);
      this.$refs["upload"].clearFiles();
      try {
        let res = await axios.get(url);
        window.URL.revokeObjectURL(url);
        this.sqlContent = res.data;
      } catch (e) {
        window.URL.revokeObjectURL(url);
        console.error(e);
        //TODO handle the exception
      }
    },
    handleDown() {
      let blob = new Blob([this.sqlContented], {
        type: "text/plain;charset=utf-8",
      });
      let downloadLink = document.createElement("a");
      downloadLink.href = window.URL.createObjectURL(blob);
      downloadLink.download = `${Date.now()}.database.${this.upFilesName}`;
      document.body.appendChild(downloadLink);
      downloadLink.click();
      window.URL.revokeObjectURL(downloadLink.href);
      document.body.removeChild(downloadLink);
    },
    handleReplace() {
      this.sqlContented = this.regData.reduce((pev, next) => {
        pev = next.fg(pev);
        return pev;
      }, this.sqlContent);
      this.$message.success("操作成功！！");
    },
    handleClean(str) {
      this[str] = "";
    },
  },
  mounted() { },
};
</script>

<style lang="scss" scoped>
::v-deep .el-textarea__inner {
  height: 200px;
}

::v-deep .el-checkbox-group {
  display: inline-block;
}

::v-deep .el-card {
  width: 100%;
}

pre {
  margin: 0;
}

.grid-content.center {
  font-size: 60px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #1890ff;
  height: 250px;
}
</style>
